<?php

include 'header.php';

if(!isset($_SESSION['user'])){
	header("Location: ".$root_path."/login.php");
}

$user = $_SESSION['user'];

$action = $_GET['action'];
$id = $_GET['id'];

$source_sites = $snsdb->get_results("select distinct(acount_source) from sns_acount where uid=".$user->id);

if($action == 'edit'){
	$task_detail = $snsdb->get_row("select * from sns_rss_task where id='".$id."'");
	
	$task_filters = $snsdb->get_results("select * from sns_task_filter where task_id='".$id."'");
	
	$reader = new XMLReader();
	$result = array();
$re = $reader->open($task_detail->rss_url);

if($re){
	while($reader->read()){
		if($reader->nodeType == XMLReader::ELEMENT){
			$item = false;
			if($reader->name == 'rss' && $reader->nodeType == XMLReader::ELEMENT){
				$item = 'item';
			}else if($reader->name == 'feed' && $reader->nodeType == XMLReader::ELEMENT){
				$item = 'entry';
			}
			break;
		}
	}
	if ($item){
		while($reader->read() ){
			if($reader->name == $item && $reader->nodeType == XMLReader::ELEMENT){
				$innerxml = $reader->readInnerXml();
				try{
					$xm = new XMLReader();
					$xm->XML('<xml>'.$innerxml.'</xml>');
					$data = array();
					while($xm->read() ){
						if($xm->name != 'xml' &&  $xm->nodeType == XMLReader::ELEMENT)
							$result[$xm->name] = $xm->name;
					}
					$xm->close();
				}catch (Exception $e){
					echo $e->getMessage();
				}
				break;
			}
		}
	}
}

$reader->close();
}

?>
        <script type="text/javascript">

        <?php if($action == 'edit'){?>


        $(document).ready(function(){
        	$("#rss_columns > li").children("input").click(function(){
        		var checked = $(this).attr('checked');
        		var name = $(this).val();
        		if(checked){
            		$("#tongbu").insertAtCaret("{"+name+"}");
        		}else{
        			var reg = $("#tongbu").val();
        			var ind = reg.indexOf("{"+name+"}");
        			if(ind != -1){
        				var s = reg.split("{"+name+"}");
        				var reg = $("#tongbu").val(s.join(""));
        			}
        		}
        	});
            });
        
        <?php }?>

        (function($) {
        	$.fn.insertAtCaret = function (tagName) {
        	return this.each(function(){
        	if (document.selection) {
	        	//IE support
	        	this.focus();
	        	sel = document.selection.createRange();
	        	sel.text = tagName;
	        	this.focus();
        	}else if (this.selectionStart || this.selectionStart == '0') {
	        	//MOZILLA/NETSCAPE support
	        	startPos = this.selectionStart;
	        	endPos = this.selectionEnd;
	        	scrollTop = this.scrollTop;
	        	this.value = this.value.substring(0, startPos) + tagName + this.value.substring(endPos,this.value.length);
	        	this.focus();
	        	this.selectionStart = startPos + tagName.length;
	        	this.selectionEnd = startPos + tagName.length;
	        	this.scrollTop = scrollTop;
        	} else {
	        	this.value += tagName;
	        	this.focus();
        	}
        	});
        	};
        	})(jQuery);

        
        	function pareseRSSSite(){
            	var rss_site = $("#rssyuan").val();
            	$("#parse_bt").removeClass("jxbg").addClass("jxbg1").attr('disabled','disabled').attr('value', '解析中..');
            	$.ajax({
                	type: 'POST',
                	url: 'parsersssite.php',
                	data: {'rsssite': rss_site},
                	success: function(data){
                    		var result = $.parseJSON(data);
                    		if(result.code == "success"){
                        		$("#publish_option_set").show();
                        		showrsscolomun(result.data);
                    		}else{
                    			showAlert(result.msg, 'error');
                    		}
                    		$("#parse_bt").removeClass("jxbg1").addClass("jxbg").removeAttr('disabled').attr('value', '解析');
                    	}
                	});
        	}

        	function showAlert(msg, type){
            	var bg = type == 'error' ? '#F1171B' : '#339506';
        		$("#alert_box").css({'left': $(document).width()/2-100, 'top': $(document).height()/2 - 300 + $(document).scrollTop(),'background': bg} );
				$("#alert_box").html(msg);
             	$("#alert_box").fadeIn().delay(3000).fadeOut();
        	}

        	function showrsscolomun(data){
            	var rss_clo_html = "";
            	var rss_fil_html = "";
            	for(var item in data){
            		rss_clo_html += "<li>";
            		rss_clo_html += "<input name=\""+item+"\" type=\"checkbox\" value=\""+item+"\"/>";
            		rss_clo_html += "<span>"+item+"</span>";
            		rss_clo_html += "</li>";

            		rss_fil_html += "<option value=\""+item+"\">"+item+"</option>";
            	}

            	$("#rss_columns").html(rss_clo_html);
            	$("#col_filter_op").html(rss_fil_html);

            	$("#rss_columns > li").children("input").click(function(){
                		var checked = $(this).attr('checked');
                		var name = $(this).val();
                		if(checked){
                    		$("#tongbu").insertAtCaret("{"+name+"}");
                		}else{
                			var reg = $("#tongbu").val();
                			var ind = reg.indexOf("{"+name+"}");
                			if(ind != -1){
                				var s = reg.split("{"+name+"}");
                				var reg = $("#tongbu").val(s.join(""));
                			}
                		}
                	});
        	}

        	function addNewFilter(){
            	$(".filter_input:last").clone().insertAfter(".filter_input:last");
            	$(".filter_input:last").children('.filter_val_name').val('');
        	}

        	function saveTask(task_start){

        		var task_name = $("#task_name").val();

        		var task_id = $("#task_id").val();

        		if(task_name == ''){
        			showAlert('请输入任务名！', 'error');
            		return;
        		}

        		var rss_site = $("#rssyuan").val();
        		var user_id = $("#user_id").val();
            	
            	var pub_colm =  $("#tongbu").val();
            	
            	if(!checkPubReg(pub_colm)){
            		showAlert('发布内容不正确，请检查！', 'error');
            		return;
            	}else if(pub_colm==""){
            		showAlert('发布内容不能空！', 'error');
            		return;
            	}

            	var filters = {};
            	$(".filter_input").each(function(index){
                	  var col_name = $(this).children(".filter_col_name").val();
                	  var op_name = $(this).children(".filter_op_name").val();
                	  var val_name = $(this).children(".filter_val_name").val();
                	  var filter_id = $(this).children(".taskfilterid").val();
                	  if(filter_id =='')
                	  	filters[index] = {'element': col_name, 'operate':op_name, 'value': val_name};
                	});

            	var filter_type = $("input:radio[name=fb]:checked").val();

            	var pub_sites = new Array();
            	$("input:checkbox[name=pub_site]:checked").each(function(index){
            		pub_sites[index] = $(this).val();
                	});

            	var min_p = $("#min_per").val();
            	var time_start = $("#time_start").val();
            	var time_end = $("#time_end").val();

            	if(!checkTime(min_p, time_start, time_end))
                	return ;

            	var pub_reg = '0 */'+min_p+" "+time_start+"-"+time_end+" * * ?";

            	var pubdata = {'task_name': task_name, 'pub_col': pub_colm, 'pub_filter': filters, 'filter_type': filter_type, 
                    	'pub_site': pub_sites.join(","), 'pub_reg': pub_reg, 'task_start': task_start, 'rsssite': rss_site,
                    	'userid': user_id, 'task_id': task_id};

            	$.ajax({
                	'type': 'POST',
                	'url': 'saversstask.php',
                	'data': pubdata,
                	'success': function(data){
                    	var result = $.parseJSON(data);
                    	if(result.code == 'success'){
                        	showAlert('已成功保存该任务', 'success');
                        	setTimeout('window.location.href="mytask.php"', 3000);
                    	}else{
                        	showAlert(result.msg, 'error');
                    	}
                	}
                	});
            	
        	}

        	function checkTime(min_p, time_start, time_end){
            	var re = /(\d){1,2}/i;
        		var m = parseInt(min_p);
        		var s = parseInt(time_start);
        		var e = parseInt(time_end);
        		if(!min_p.match(re)){
        			showAlert("分钟数必须为数字", 'error');
            		return false;
        		}else{
            		if(m>60 || m<0){
                		showAlert("分钟数不能超过60或小于0", 'error');
                		return false;
            		}
        		}

        		if(!time_start.match(re)){
        			showAlert("开始时间必须为数字", 'error');
            		return false;
        		}else{
            		if(s>23 || m<0){
                		showAlert("开始小时数不能超过24或小于0", 'error');
                		return false;
            		}
        		}

        		if(!time_end.match(re)){
        			showAlert("结束时间必须为数字", 'error');
            		return false;
        		}else{
            		if(e>60 || e<0){
                		showAlert("结束小时数不能超过60或小于0", 'error');
                		return false;
            		}
        		}

        		if(e< s){
        			showAlert("结束小时数不能小于开始时间", 'error');
            		return false;
        		}
        		return true;
        		
        	}

        	function deletetaskfilter(){
        		var target = jQuery(window.event.srcElement);
        		var tf_id = target.prev().attr('value');
        		if(tf_id != ''){
	        		$.ajax({
	                	'type': 'POST',
	                	'url': 'opreatetask.php',
	                	'data': {'id': tf_id, 'op': 'detf'},
	                	'success': function(data){
	                        showAlert('已成功删除该过滤条件！', 'success');
	                        target.parent().remove();
	                	}
                	});
        		}else{
        			if($(".filter_input").length <= 1){
        				showAlert('不能删除该条目！', 'error');
        			}else
        				target.parent().remove();
        		}
        	}


        	function checkPubReg(pub_reg){
            	var flag = false;
            	for(var i=0; i<pub_reg.length; i++){
                	var s = pub_reg.charAt(i);
                	if(s == '{'){
                    	if(!flag)
                        	flag = true;
                    	else
                        	return false;
                	}else if(s == "}"){
                    	if(flag)
                        	flag = false;
                    	else
                        	return false;
                	}
            	}
            	return true;
        	}
        </script>
   
                <div id="sider_left">
                	<img src="images/b_sider_top.jpg" width="207" height="7" class="imgfloat" />
                    	<ul>
                        	<li id="weixuan"><a href="myacounts.php">我的账号</a></li>
                            <li id="xuanzhong">我的任务</li>
                        </ul>
                    <img src="images/b_sider_buttom.jpg" width="207" height="7" class="imgfloat" />
                </div>
                <div id="sider_right">
                	<img src="images/sider_righttop.jpg" width="642" height="6" class="imgfloat" />
                    	<form>
                        	<div id="sr_top">
                        		<span class="addtitle">任务名称</span>
                                <span class="jiexi">
                                	<input type="text" id="task_name" name="task_name" class="rssyuan"
                                	value="<?php echo $task_detail->title;?>" />
                                	<input type="hidden" id="user_id" value="<?php echo $user->id;?>" />
                                	<input type="hidden" id="task_id" value="<?php echo $task_detail->id;?>"/>
                                </span>
                        		<span class="addtitle">输入需要定时发布的RSS源</span>
                                <span class="jiexi">
                                	<input type="text" id="rssyuan" name="rssyuan" class="rssyuan" 
                                	value="<?php echo $task_detail->rss_url;?>"/>
                                    <input type="button" value="解析" id="parse_bt" class="jxbg" onclick="pareseRSSSite()"/>
                                </span>
                                <div id="publish_option_set" style="<?php if($action != 'edit') echo "display: none;";?>">
	                                <span class="addtitle" style="margin-top:10px;">该RSS源中可选发布字段</span>
	                                <div id="publish_reg" class="jiexi">
	                                	<span id="jxt">顺序选择需要发布字段，系统将根据选择的字段内容顺序排列，字数超出时后面的字段可能会裁切</span>
	                                	<ul id="rss_columns">
	                                		<?php foreach ($result as $ree){?>
	                                		<li>
	                                			<input name="<?php echo $ree;?>" type="checkbox" value="<?php echo $ree;?>" <?php if (stripos($task_detail->forward_content, trim($ree))) echo "checked='checked'";?> />
	                                			<span><?php echo $ree;?></span>
	                                		</li>
	                                		<?php }?>
	                                	</ul>
	                                   <span id="yiwen">
	                                   		<input type="text" id="tongbu" value="<?php echo $task_detail->forward_content;?>" />
	                                        <a href="#" name="有疑问？请点击"><img src="images/yiwen.jpg" width="52" height="35" alt="有疑问？请点击" title="有疑问？请点击" style="float:left; margin-top:-5px;" /></a>
	                                   </span>
	                                </div>
	                                <span class="addtitle" style="margin-top:10px;">内容过滤</span>
	                                <div id="publish_filter" class="jiexi">
	                                 	<span style="float: right; margin-top: 10px; margin-right: 10px;"><input type="button" onclick="addNewFilter()" value="添加新过滤规则" id="addbutton" /></span>
	                                	
	                                	<?php foreach($task_filters as $task_filter){?>
	                                	<span class="jxspan filter_input" >
	                                    	当前字段
	                                        <select id="col_filter_op" name="" class="filter_col_name">
	                                        	<?php foreach ($result as $ree){?>
	                                        		<option value="<?php echo $ree;?>" <?php if($ree==$task_filter->element) echo "selected='selected'";?>><?php echo $ree;?></option>
	                                        	<?php }?>
	                                        </select>
	                                        <select name="" class="filter_op_name">
	                                        	<option value="eq" <?php if($task_filter->operate == 'eq') echo "selected='selected'";?>>等于</option>
	                                            <option value="co" <?php if($task_filter->operate == 'co') echo "selected='selected'";?>>包含</option>
	                                            <option value="uncon" <?php if($task_filter->operate == 'uncon') echo "selected='selected'";?>>不包含</option>
	                                        </select>
	                                        <input type="text" id="addgz"  value="<?php echo $task_filter->value;?>" class="filter_val_name" />
	                                        <input type="hidden" class="taskfilterid" value="<?php echo $task_filter->id;?>" />
	                                        <a href="javascript:void(0);" onclick="deletetaskfilter();">删除</a>
	                                    </span>
	                                	<?php }?>
	                                	<span class="jxspan filter_input" >
	                                    	当前字段
	                                        <select id="col_filter_op" name="" class="filter_col_name">
	                                        	<?php foreach ($result as $ree){?>
	                                        		<option value="<?php echo $ree;?>"><?php echo $ree;?></option>
	                                        	<?php }?>
	                                        </select>
	                                        <select name="" class="filter_op_name">
	                                        	<option value="eq" selected="selected">等于</option>
	                                            <option value="co">包含</option>
	                                            <option value="uncon">不包含</option>
	                                        </select>
	                                        <input type="text" id="addgz"  value="" class="filter_val_name" />
	                                         <input type="hidden" class="taskfilterid" value="" />
	                                        <a href="javascript:void(0);" onclick="deletetaskfilter();">删除</a>
	                                    </span>
	                                    <span class="jxspan" id="pipei" >
	                                    	当内容匹配以上规时
	                                       <input type="radio" checked="checked" name="fb" value="pub" />发布
	                                       <input type="radio" name="fb" value="nonpub" />不发布     
	                                    </span>
	                                   
	                                </div>
	                                <span class="addtitle" style="margin-top:10px;">发布到账号</span>
	                                <div id="publish_site" class="jiexi">
	                                	<ul>
	                                	<?php foreach ($source_sites as $site){
	                                	?>
	                                		<li>
		                                		<input name="pub_site" type="checkbox" value="<?php echo $site->acount_source; ?>" <?php if(stripos("pre".$task_detail->forward_site, $site->acount_source)) echo "checked='checked'"?> /> 
	                                			<img src="images/<?php echo $site->acount_source;?>.png" alt="" />
		                                        <span><?php if($site->acount_source == 'tencent') echo '腾讯微博';elseif ($site->acount_source == 'sina') echo '新浪微博';?></span>
	                                		</li>
	                                	<?php }?>
	                                	</ul>
	                                </div> 
	                                <span class="addtitle" style="margin-top:10px;">设置时间发布规则</span>
	                                <?php 
	                                if($task_detail){
	                                	$reg = explode(" ", $task_detail->forward_regularly);
	                                	$min = explode("/", $reg[1]);
	                                	$time = explode("-", $reg[2]);
	                                }
	                                ?>
	                                <div id="publish_time" class="jiexi">
	                                	<span class="jxspan" >每隔<input id="min_per" type="text" class="timegz" name="" value="<?php echo $min[1];?>" title="值应为0到60之间的值" />分钟发布一次。发布时间范围在
	                                	<input id="time_start" type="text" class="timegz" name="" value="<?php echo $time[0];?>" title="值应为0到23之间的值" />时至
	                                	<input id="time_end" type="text" class="timegz" name="" value="<?php echo $time[1];?>" title="值应为0到23之间的值"/>时</span>
	                                    <input type="button" value="取消" id="quxiao" class="bj" onclick="window.location.href='mytask.php'" />
	                                    <input type="button" value="只保存任务" id="zbc" class="bj" onclick="saveTask(2);" />
	                                    <input type="button" value="保存并启动该任务" id="bzqd" class="bj" onclick="saveTask(1);" />
	                                </div>
                                </div>
                            </div>
                        </form>
                    <img src="images/sider_rightbuttom.jpg" width="642" class="imgfloat" />
                </div>
        	<img src="images/container_buttom.gif" width="880" height="12" class="imgfloat" />
        </div>
        <div id="alert_box"></div>
    </body>
</html>
